package filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化过滤器，可以设置一些配置参数
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 记录请求的开始时间
        long startTime = System.currentTimeMillis();
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String requestURI = httpRequest.getRequestURI();
        if (!requestURI.equals("/web/") && !requestURI.contains("code") && !requestURI.contains("login") && !requestURI.contains("resources") &&
                !requestURI.contains("register")) {
            Object info = ((HttpServletRequest) request).getSession().getAttribute("info");
            if (info == null) {
                httpResponse.sendRedirect("/web/login.jsp");
                return;
            }
        }
        // 将请求和响应传递给过滤器链的下一个组件
        chain.doFilter(request, response);
        System.out.println("Request URI: " + requestURI);
        System.out.println("Request Method: " + httpRequest.getMethod());
        // 记录请求的结束时间
        long endTime = System.currentTimeMillis();
        // 打印请求信息
        System.out.println("Request Time: " + (endTime - startTime) + " ms");


    }

    @Override
    public void destroy() {
        // 销毁过滤器，释放资源
    }
}